#!/bin/sh
#
# Starts dropbear sshd.
#

echo "Top of dropbear init script"

# Allow a few customizations from a config file
test -r /etc/default/dropbear && . /etc/default/dropbear

start() {
	DROPBEAR_ARGS="$DROPBEAR_ARGS -R"

	echo -n "Starting dropbear sshd: "
	umask 077
	local dropbear_key_dir="/etc/dropbear"

	# If /etc/dropbear is not a directory, and
	#   - the filesystem is RO (i.e. we can not rm the symlink),
	#     create the directory pointed to by the symlink.
	#   - the filesystem is RW (i.e. we can rm the symlink),
	#     replace the symlink with an actual directory
	if ! [ -d /etc/dropbear ]; then
		if ! rm -f /etc/dropbear; then
			dropbear_key_dir=$(readlink "$dropbear_key_dir")
		fi
	fi

	# Ensure host keys are changed when instance ID changes
	cirros-per instance remove-dropbear-host-keys -- rm -rf "$dropbear_key_dir"
	mkdir -p "$dropbear_key_dir"

	# Regenerate invalid or missing keys
	local ktype file
	for ktype in rsa ecdsa ed25519; do
		file="${dropbear_key_dir}/dropbear_${ktype}_host_key"
		# -f = input file, -y = validate and print pubkey info
		if ! dropbearkey -f "$file" -y &>/dev/null; then
			if [ -e "$file" ]; then
				echo "Removing invalid key: $file"
				rm -f "$file"
			fi
			# -t = type (rsa, ecdsa), -f = output file
			dropbearkey -t "$ktype" -f "$file" >/dev/null 2>&1 ||
		echo "WARN: generating key of type $ktype failed!"
		fi
	done
	start-stop-daemon -S -q -p /var/run/dropbear.pid \
		--exec /usr/sbin/dropbear -- $DROPBEAR_ARGS
	[ $? = 0 ] && echo "OK" || echo "FAIL"
}
stop() {
	echo -n "Stopping dropbear sshd: "
	start-stop-daemon -K -q -p /var/run/dropbear.pid
	[ $? = 0 ] && echo "OK" || echo "FAIL"
}
restart() {
	stop
	start
}

case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart|reload)
  	restart
	;;
  *)
	echo "Usage: $0 {start|stop|restart}"
	exit 1
esac

exit $?
